package com.android.lovely.framework

import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commitNow
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.android.lovely.R
import com.android.lovely.ext.fullScreen
import com.kotlin.extensions.context.ActivityExt.statusBarColor
import java.lang.reflect.ParameterizedType

/**
 *
 * @author why
 * @date 2025/3/7 15:15
 */
abstract class BaseDialogFragment<VB : ViewBinding> : DialogFragment() {

    val binding: VB by lazy { inflateBinding() }
    private var onDialogListener: OnDialogListener? = null

    inline val viewLifecycleScope get() = viewLifecycleOwner.lifecycleScope

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.BaseDialogTheme)
    }

    override fun onDismiss(dialog: DialogInterface) {
        onDialogListener?.onDialogDismiss()
        super.onDismiss(dialog)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        onDialogListener = null
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        setupDialogWindow()
        return binding.root
    }

    private fun setupDialogWindow() {
        dialog?.window?.let { window ->
            window.requestFeature(Window.FEATURE_NO_TITLE)
            window.setBackgroundDrawableResource(R.color.transparent)
            window.decorView.setPadding(0, 0, 0, 0)

            // 允许窗口扩展到状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            // 设置状态栏背景为透明
            window.statusBarColor = Color.WHITE




            val layoutParams = window.attributes.apply {
                width = getWindowWidth()
                height = getWindowHeight()
                gravity = if (isBottom()) Gravity.BOTTOM else Gravity.CENTER
//                if (isBottom()) {
//                    windowAnimations = R.style.anim_bottom_dialog
//                }
            }
            window.attributes = layoutParams
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initializeViews()
    }

    fun setOnDismissListener(listener: OnDialogListener): BaseDialogFragment<*> {
        onDialogListener = listener
        return this
    }

    open fun isBottom(): Boolean = false

    open fun getWindowHeight(): Int = WindowManager.LayoutParams.WRAP_CONTENT

    open fun getWindowWidth(): Int = WindowManager.LayoutParams.MATCH_PARENT

    abstract fun initializeViews()

    private fun inflateBinding(): VB {
        val bindingClass =
            (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VB>
        val method = bindingClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as VB
    }

    fun show(fragmentManager: FragmentManager) {
        // 捕获可能的异常
        runCatching {
            val existingFragment = fragmentManager.findFragmentByTag(javaClass.name)
            existingFragment?.takeIf { it.isAdded }?.let {
                fragmentManager.commitNow { remove(it) }
            }
            // 显示当前对话框片段
            super.show(fragmentManager, javaClass.name)
        }.onFailure {
            // 处理异常，这里简单打印日志，实际使用中可以根据需求进行处理
            it.printStackTrace()
        }
    }

    interface OnDialogListener {
        fun onDialogDismiss()
    }
}